<?php
if(!defined('IN_KKFRAME')) exit();

if($_GET['logout'] && $_GET['logout']==$formhash){
	dsetcookie('auth', '');
	$_COOKIE['auth'] = '';
	showmessage('您已经退出登录了！', referer(), 1);
}elseif($uid){
	showmessage('您已经登录了~', referer(), 1);
}elseif($_GET['do'] == 'register'){
	if($_POST){
		if(!$_POST['username']){
			showmessage('请输入用户名', 'member.php?do=register');
		}elseif(!$_POST['password']){
			showmessage('请输入密码', 'member.php?do=register');
		}elseif(!$_POST['email']){
			showmessage('请输入您的邮箱', 'member.php?do=register');
		}else{
			$username = daddslashes($_POST['username']);
			$email = daddslashes($_POST['email']);
			$password = md5($_POST['password']);
			if(!$username || !$password || !$email) showmessage('您输入的信息不完整', 'member.php?do=register');
			if(preg_match('/[^a-zA-Z0-9]/i', $username)) showmessage('您输入的用户名不合法，用户名仅允许字母和数字！', 'member.php?do=register');
			if(strlen($username) < 3) showmessage('用户名至少要3位，请修改', referer(), 5);
			$un = strtolower($username);
			if(strexists($un, 'admin') || strexists($un, 'guanli')) showmessage('用户名不和谐，请修改', referer(), 5);
			$user = DB::fetch_first("SELECT * FROM user WHERE username='{$username}'");
			if($user) showmessage('用户名已经存在', 'member.php?do=register');
			$uid = DB::insert('user', array(
				'username' => $username,
				'password' => $password,
				'email' => $email,
				'adminid' => 0,
			));
			dsetcookie('auth', authcode("{$uid}\t{$username}", 'ENCODE'));
			send_notice($uid, "{$username}，十分感谢您的注册，您已成为本论坛的注册会员，请您在发表言论时务必遵守相关法律或规定，以免与我们的管理团队产生不必要的矛盾，谢谢！");
			showmessage("注册成功，您的用户名是 <b>{$username}</b> 记住了哦~！", referer(), 3);
		}
	}
	include template('register');
	exit();
}elseif($_POST){
	if($_POST['username'] && $_POST['password']){
		$username = daddslashes($_POST['username']);
		$password = md5($_POST['password']);
		$un = strtolower($username);
		if(strlen($username) >= 18) showmessage('用户名过长，请修改', referer(), 5);
		$user = DB::fetch_first("SELECT * FROM user WHERE username='{$username}' AND password='{$password}'");
		$username = $user['username'];
		if($user) {
			$uid = $user['uid'];
			dsetcookie('auth', authcode("{$uid}\t{$username}", 'ENCODE'));
			showmessage("欢迎回来，{$username}！", referer(), 1);
		}else{
			showmessage('对不起，您的用户名或密码错误，无法登录.', 'member.php?do=login', 3);
		}
	}
}
include template('login');